<?php
use Carbon\Carbon;
class OrderController extends RestrictedBaseController {
	
	public function index() {
		$customers = array('' => 'Todos os clientes') + Customer::orderBy('name')->get()->lists('name', 'id');
		$this->layout->content = View::make('order.index')->with('customers', $customers);
	}
	
	public function getList() {
		$this->layout = null;
		$result = Order::getOrders($this->assembleFilterOptions(), Input::get('iDisplayStart'), Input::get('iDisplayLength'));
		
		return Response::json(array(
			"sEcho" => intval(Input::get('sEcho')),
			"iTotalRecords" => $result['total'],
			"iTotalDisplayRecords" => $result['total'],
			"aaData" => $result['data']
		));
	}
	
	public function getExecutedList() {
		$this->layout = null;
		$result = Order::getExecutedOrders($this->assembleFilterOptions(), Input::get('iDisplayStart'), Input::get('iDisplayLength'));
	
		return Response::json(array(
			"sEcho" => intval(Input::get('sEcho')),
			"iTotalRecords" => $result['total'],
			"iTotalDisplayRecords" => $result['total'],
			"aaData" => $result['data']
		));
	}
	
	public function getByOrderNumber($orderNumber) {
		$this->layout = null;
		
		return Response::json(
			Order::where('order_number', '=', $orderNumber)
				->get(array('production_number', 'order_date', 'customer_id'))
		);
	}
	
	public function create() {
		$customers = array('' => '') + Customer::orderBy('name')->get()->lists('name', 'id');
		
		$this->layout->content = View::make('order.create')
			->with('products', Product::orderBy('name')->get()->toJson())
			->with('customers', $customers)
			->with('costsCentres', CostsCentre::orderBy('id')->get()->toJson())
			->with('oldAccessories', Input::old('accessories'))
			->with('oldCigamCodes', Input::old('cigamCodes'))
			->with('oldComponents', Input::old('components'))
			->with('oldCostCentres', Input::old('costCentres'))
			->with('oldAmounts', Input::old('amounts'));
	}
	
	public function store() {
		$rules = Order::assembleValidation(Input::all());
		$validator = Validator::make(Input::all(), $rules);
	
		if ($validator->fails()) {
			return Redirect::to('order/create')
				->withErrors($validator)
				->withInput(Input::all());
		} else {
			//TODO: minimizar codigo no controller
			DB::transaction(function() {
				$order = new Order();
				$order->order_number = Input::get('order_number');
				$order->customer_id = Input::get('customer_id');
				$order->production_number = Input::get('production_number');
				$order->amount = Input::get('amount');
				// TODO: automatizar conversao das datas
				$order->order_date = Carbon::createFromFormat('d/m/Y', Input::get('order_date'))->format('Y-m-d');
				$order->production_start_date = Carbon::createFromFormat('d/m/Y', Input::get('production_start_date'))->format('Y-m-d');
				$order->production_end_date = Carbon::createFromFormat('d/m/Y', Input::get('production_end_date'))->format('Y-m-d');
				// TODO: automatizar adição do usuário
				$order->user_id = Auth::user()->id;
				$order->save();
					
				foreach (Input::get('components') as $key => $componentName) {
					$component = Component::where('name', '=', $componentName)->where('code', '=', Input::get('cigamCodes')[$key])->first();
	
					if (empty($component)) {
						$component = new Component();
						$component->accessory = Input::get('accessories')[$key];
						$component->code = Input::get('cigamCodes')[$key];
						$component->name = $componentName;
						$component->user_id = Auth::user()->id;
						$component->save();
					}
	
					$orderComponent = new OrderComponent();
					$orderComponent->order_id = $order->id;
					$orderComponent->component_id = $component->id;
					$orderComponent->user_id = Auth::user()->id;
					$orderComponent->amount = Input::get('amounts')[$key];
					$orderComponent->current_step = 1;
					$orderComponent->save();
					
					$costCentres = explode(",", Input::get('costCentres')[$key]);
					
					foreach ($costCentres as $key => $costCentre) {
						$productionStep = new ProductionStep();
						$productionStep->costs_centre_id = $costCentre;
						$productionStep->order_component_id = $orderComponent->id;
						$productionStep->step = $key + 1;
						$productionStep->user_id = Auth::user()->id;
						$productionStep->save();
					}
				}
			});
	
			Session::flash('message', 'Pedido incluído com sucesso');
			return Redirect::to('order');
		}
	}
	
	public function edit($id) {
		$order = Order::find($id);
		$customers = array('' => '') + Customer::orderBy('name')->get()->lists('name', 'id');
	
		$this->layout->content = View::make('order.edit')
			->with('order', $order)
			->with('customers', $customers)
			->with('customer', Customer::find($order->customer_id, array('name')))
			->with('orderComponents', OrderComponent::whereOrderWithComponents($id)->get())
			->with('costsCentres', CostsCentre::orderBy('id')->get()->toJson())
			->with('canEditProductionStart', $order->canEditProductionStart())
			->with('oldDisabledComponents', Input::old('disabledComponents'))
			->with('oldAccessories', Input::old('accessories'))
			->with('oldCigamCodes', Input::old('cigamCodes'))
			->with('oldComponents', Input::old('components'))
			->with('oldCostCentres', Input::old('costCentres'))
			->with('oldAmounts', Input::old('amounts'));
	}
	
	public function update($id) {
		$order = Order::find($id);
		$canEditProductionStart = $order->canEditProductionStart();
		
		$input = Input::all();
		if (!$canEditProductionStart) {
			$input['production_start_date'] = $order->production_start_date->format('d/m/Y');
		}
		
		$rules = Order::assembleValidation($input);
		$validator = Validator::make($input, $rules);
	
		if ($validator->fails()) {
			return Redirect::to("order/{$id}/edit")
				->withErrors($validator)
				->withInput(Input::all());
		} else {
			DB::transaction(function() use ($id, $order, $canEditProductionStart) {
				$order->order_number = Input::get('order_number');
				$order->customer_id = Input::get('customer_id');
				$order->production_number = Input::get('production_number');
				$order->amount = Input::get('amount');
				// TODO: automatizar conversao das datas
				$order->order_date = Carbon::createFromFormat('d/m/Y', Input::get('order_date'))->format('Y-m-d');
				if ($canEditProductionStart) {
					$order->production_start_date = Carbon::createFromFormat('d/m/Y', Input::get('production_start_date'))->format('Y-m-d');
				}
				$order->production_end_date = Carbon::createFromFormat('d/m/Y', Input::get('production_end_date'))->format('Y-m-d');
				// TODO: automatizar adição do usuário
				$order->user_id = Auth::user()->id;
				$order->save();
				
				$currentOrderComponents = OrderComponent::where('order_id', '=', $id)->lists('id');
				$disabledComponents = Input::get('disabledComponents');
				$inputOrderComponents = array();
				
				foreach (Input::get('components') as $key => $componentName) {
					if (!isset($disabledComponents[$key])) {
						$component = Component::where('name', '=', $componentName)->where('code', '=', Input::get('cigamCodes')[$key])->first();
						
						if (empty($component)) {
							$component = new Component();
							$component->accessory = Input::get('accessories')[$key];
							$component->code = Input::get('cigamCodes')[$key];
							$component->name = $componentName;
							$component->user_id = Auth::user()->id;
							$component->save();
						}

						$orderComponent = new OrderComponent();
						$orderComponent->order_id = $order->id;
						$orderComponent->component_id = $component->id;
						$orderComponent->user_id = Auth::user()->id;
						$orderComponent->current_step = 1;
						$orderComponent->amount = Input::get('amounts')[$key];
						$orderComponent->save();
						
						$orderComponent->costsCentres()->detach();
						$costCentres = explode(",", Input::get('costCentres')[$key]);
						
						if (!empty($costCentres)) {
							foreach ($costCentres as $key => $costCentre) {
								$productionStep = new ProductionStep();
								$productionStep->costs_centre_id = $costCentre;
								$productionStep->order_component_id = $orderComponent->id;
								$productionStep->step = $key + 1;
								$productionStep->user_id = Auth::user()->id;
								$productionStep->save();
							}
						}
						
						array_push($inputOrderComponents, $orderComponent->id);
					} else {
						$orderComponent = OrderComponent::where('order_id', '=', $order->id)
							->where('component_id', '=', $key)
							->first();
						array_push($inputOrderComponents, $orderComponent->id);
					}
				}
				
				$detachedComponents = array_diff($currentOrderComponents, $inputOrderComponents);
				if (!empty($detachedComponents)) {
					foreach ($detachedComponents as $detachedComponentId) {
						$orderComponent = OrderComponent::find($detachedComponentId);
						
						$orderComponent->costsCentres()->detach();
						$orderComponent->logs()->delete();
						$orderComponent->delete();
					}
				}
			});
					
			Session::flash('message', 'Pedido atualizado com sucesso');
			return Redirect::to('order');
		}
	}
	
	public function destroy($id) {
		DB::transaction(function() use ($id) {
			$order = Order::find($id);
			
			$orderComponents = OrderComponent::where('order_id', '=', $order->id)->get();
			foreach($orderComponents as $orderComponent) {
				$orderComponent->costsCentres()->detach();
				$orderComponent->logs()->delete();
			}
			
			$order->components()->detach();
			$order->delete();
		});
	
		Session::flash('message', 'Pedido excluído com sucesso');
		return Redirect::to('order');
	}
	
	public function viewDetails($id) {
		$this->layout = null;
		
		$order = Order::with(array('customer'))->find($id);
		$components = OrderComponent::getComponentsByOrder($id);
		
		return View::make('order.view')
			->with('order', $order)
			->with('components', $components);
	}
	
	private function assembleFilterOptions() {
		$options = array();
		$options['orderNumber'] = Input::get('orderNumber');
		$options['productionNumber'] = Input::get('productionNumber');
		$options['customerId'] = Input::get('customerId');
		$options['onlyCompleted'] = Input::get('onlyCompleted');
	
		return $options;
	}
}